import os
import re

HEADER = '''/*
 * 作者：坚果派
 * 公众号：nutpi
 * 电话：17752170152
 * 官网：https://www.nutpi.net/
 */

'''

excluded_dirs = {'build', '.git', '.idea', 'ios', 'android', 'ohos', 'web', 'lib/constants'}

def should_exclude(path):
    return any(ex_dir in path for ex_dir in excluded_dirs)

def process_file(filepath):
    with open(filepath, 'r+', encoding='utf-8') as f:
        content = f.read()
        
        # 跳过已包含版权的文件
        if re.search(r'\*\s*作者：坚果派', content):
            return False
            
        # 保留原有编码声明
        bom = b''
        if content.startswith('\ufeff'):
            content = content[1:]
            bom = b'\xef\xbb\xbf'
        
        new_content = bom.decode('utf-8') + HEADER + content
        
        f.seek(0)
        f.write(new_content)
        f.truncate()
        return True

def main():
    project_root = os.path.dirname(os.path.abspath(__file__))
    count = 0
    
    for root, dirs, files in os.walk(project_root):
        # 过滤不需要遍历的目录
        dirs[:] = [d for d in dirs if not should_exclude(os.path.join(root, d))]
        
        for file in files:
            if file.endswith('.dart'):
                filepath = os.path.join(root, file)
                try:
                    if process_file(filepath):
                        print(f'成功处理: {filepath}')
                        count += 1
                except Exception as e:
                    print(f'处理失败 {filepath}: {str(e)}')
    
    print(f'\n操作完成，共处理{count}个Dart文件')

if __name__ == '__main__':
    main()